package com.example.ccj.b.c.ui.install;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.MImageView;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.media.MediaUtils;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

/**
 * 添加选项的Adapter
 * 2024年4月24日21:08:57
 */
public class AddOptionAdapter extends RecyclerView.Adapter<AddOptionAdapter.ViewHolder>{
    List<String> optionList;

    /**
     * @param optionList  图片列表
     */
    public AddOptionAdapter(List<String> optionList){
        this.optionList = optionList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).
                inflate(R.layout.adapter_add_option, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String s = optionList.get(position);
        holder.id.setText(String.valueOf(position + 1));
        holder.optionText.setText(s);
        holder.mIvDelete.setOnClickListener(getDeleteClickListener(position));
    }

    private View.OnClickListener getDeleteClickListener(int position){
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notifyRemove(position);
            }
        };
    }

    @Override
    public int getItemCount() {
        return optionList == null ? 0 : optionList.size();
    }

    public static class ViewHolder extends  RecyclerView.ViewHolder{
        ImageView mIvDelete;
        EditText optionText;
        TextView id;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mIvDelete = itemView.findViewById(R.id.adapter_add_option_delete);
            optionText = itemView.findViewById(R.id.adapter_add_option_text);
            id = itemView.findViewById(R.id.adapter_add_option_id);

        }
    }

    private void notifyRemove(int position){
        optionList.remove(position);
        notifyItemRemoved(position);
        //重新加载从删除位置往下的所有item，如果删除的是中间，自删除的位置到最后开始是做重新添加操作
        //避免下表越界等错误
        notifyItemRangeRemoved(position,getItemCount());
    }

}
